<?php


namespace app\api\controller;


use app\api\model\MeetConfigModel;
use app\api\model\MeetModel;
use app\api\model\Wxconfig;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\library\WXBizMsgCrypt;
use think\Cache;
use function fast\e;
use fast\Random;

class Userinfo extends Api
{
    protected $noNeedLogin = ['wxlogin','authUrl','applyid','callbackverify','openFileInit','huiyiverify','approvalCallback'];
    protected $noNeedRight = '*';

    public function openFileInit()
    {
        $url = input('url');
        if(empty($url)){
             $this->error('url必传');
        }
        $config = MeetConfigModel::config($url);
        $corpid = $config['corpid'];
        $secret = $config['Secret'];
        $AgentId = $config['AgentId'];
        $api_data = MeetConfigModel::getAccessToken($corpid,$secret);

        $noncestr = uniqid();
        $timestamp = time();
        $url = urldecode($url);
        $jsapi_ticket = MeetConfigModel::getTicket($api_data['access_token']);
        $signature = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $sign = sha1($signature);
        $data1 = [
            'corpid' => $corpid,
            'agentid' => $AgentId,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $sign,
            //'jsApiList' => ['previewFile','chooseImage','previewImage','uploadImage','checkJsApi','agentConfig'],
            //'jsApiList' => ['previewFile'],
            'jsApiList' => ['previewFile','downloadImage','scanQRCode','chooseImage','previewImage','uploadImage','selectEnterpriseContact'],
            'url' => $url,
            'jsapi_ticket' => $jsapi_ticket,
        ];
        $jsapi_ticket = MeetConfigModel::getAppTicket($api_data['access_token']);
        $signature = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $sign = sha1($signature);
        $data2 = [
            'corpid' => $corpid,
            'agentid' => $AgentId,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $sign,
            'jsApiList' => ['previewFile','downloadImage','scanQRCode','chooseImage','previewImage','uploadImage','selectEnterpriseContact'],
            //'jsApiList' => ['previewFile'],
            'url' => $url,
            'jsapi_ticket' => $jsapi_ticket,
        ];
        $data = [
            'qiye' => $data1,
            'app' => $data2
        ];
        $this->success('成功',$data);
    }

    public function info()
    {
        $user = $this->auth->getUserinfo();
        $this->success('成功',$user);
    }

    public function authUrl()
    {
        $url = '';
        $path = input('path');
        if($path){
            $url = urldecode($path);
        }
        $REDIRECT_URI = request()->domain().$url;
        if(!empty($path)){
            $REDIRECT_URI = urlencode($REDIRECT_URI);
        }
        $config = MeetConfigModel::config($REDIRECT_URI);
        $corpid = $config['corpid'];
        $AGENTID = $config['AgentId'];
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$corpid.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid='.$AGENTID.'#wechat_redirect';
        $data = [
            'url' => $url,
        ];
        $this->success('成功',$data);
    }

    public function wxlogin()
    {
        $code = input('code');
        $path = input('path');
        $config = MeetConfigModel::config($path);
        $corpid = $config['corpid'];
        $secret = $config['Secret'];
        $AgentId = $config['AgentId'];

        //echo $AgentId;die();
        $api_data = MeetConfigModel::getAccessToken($corpid,$secret);
        $infourl = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$api_data['access_token'].'&code='.$code;
        $client = new \GuzzleHttp\Client();
        $result = $client->get($infourl)->getBody()->getContents();
        $infodata = json_decode($result, true);
        log_print('infodata');
        log_print($infodata);
        /*
            [UserId] => 18820268653
            [DeviceId] => fcfda3cb-133d-4f63-abf5-584b397355d8
            [errcode] => 0
            [errmsg] => ok
            [user_ticket] =>
            [expires_in] => 1800
         * */
        if($infodata['errmsg'] != 'ok'){
            log_print('获取userinfo出错');
            log_print($infodata['AgentId'] = $AgentId);
            $this->error('获取用户信息错误1',$infodata);
        }
        $UserId = $infodata['UserId'];
//        Cache::rm('wxlogin_wx_userid_'.$UserId);
        if(Cache::has('wxlogin_wx_userid_'.$UserId))
        {
            $this->error('重复请求');
        }else{
            Cache::set('wxlogin_wx_userid_'.$UserId, 1, 30);
        }
        log_print('Cache____'.Cache::get('wxlogin_wx_userid_'.$UserId));//xj
        $map = [
            'wx_userid' => $UserId
        ];
        //$user = \app\common\model\User::getByMobile($mobile);
        $user = \app\common\model\User::where($map)->find();
        if ($user && !empty($user['avatar']) && strlen($user['mobile']) == 11) {
            if(strpos($user['AgentId'],$AgentId) === false){
                $user->AgentId .= ','.$AgentId;
                $user->save();
            }
            //如果已经有账号则直接登录
            $this->auth->direct($user->id);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }
        //print_r($infodata);
        if(!empty($infodata['user_ticket'])){
            $option = [
                'user_ticket' => $infodata['user_ticket'],
            ];
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token='.$api_data['access_token'];
            $client = new \GuzzleHttp\Client();
            $res = $client->request('POST', $url, [
                'json' => $option,
            ]);
            $req = $res->getBody()->getContents();
            $detail = json_decode($req, true);
            //print_r($detail);die();
            log_print('getuserdetail');
            log_print($detail);
            if($detail['errmsg'] != 'ok'){
                log_print('获取getuserdetail出错');
                log_print($detail);
                $this->error('获取用户信息错误2',$detail);
            }
        }
        $avatar = '';
        if(!empty($detail['avatar'])){
            $avatar = $detail['avatar']; //拿到头像
        }
        $mobile = '';
        if(!empty($detail['mobile'])){
            $mobile = $detail['mobile'];
        }
        $durl = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$api_data['access_token'].'&userid='.$UserId; //读取通讯录资料
        $client = new \GuzzleHttp\Client();
        $result = $client->get($durl)->getBody()->getContents();
        $wxuser = json_decode($result, true);
        log_print('$wxuser');
        log_print($wxuser);
        if($wxuser['errmsg'] != 'ok'){
            log_print('获取通讯录出错');
            log_print($wxuser);
            $this->error('获取用户信息错误3',$wxuser);
        }
        //$name = $mobile;
        $name = '';
        if(!empty($wxuser['name'])){
            $name = $wxuser['name'];
        }
        $map = [
            'wx_userid' => $UserId
        ];
        $user = \app\common\model\User::where($map)->find();
        if ($user) {
            //if(){}
            if($mobile && empty($user['mobile'])){
                $user->mobile = $mobile;
            }
            if($name && empty($user['nickname'])){
                $user->nickname = $name;
            }
            if(strpos($user['AgentId'],$AgentId) === false){
                $user->AgentId .= ','.$AgentId;
            }
            if($avatar){
                $user->avatar = $avatar;
            }
            $user->save();
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ext = [
                'avatar' => $avatar,
                'nickname' => $name,
                'username' => $UserId,
                'wx_userid' => $UserId,
                'AgentId' => $AgentId,
            ];
            $ret = $this->auth->register($UserId, Random::alnum(), '', $mobile, $ext);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function callbackverify(){
        $encodingAesKey = "P8oQ8KVqb3303FORvH7HvIFstNLCOguOmR6l1DYV6bC";
        $token = "agcKoqdLcGuobKQ6VmgYxMfw";
        $receiveid = "ww377c91a81493c595";

        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);

        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = $_GET['echostr'];

        $sEchoStr = "";
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            log_print($sEchoStr);
        	// 验证URL成功
            return $sEchoStr;
        } else {
            log_print('回调失败');
            log_print("ERR: " . $errCode);
            return '回调失败';
        }
    }


    public function huiyiverify(){
        $encodingAesKey = "ZlJbw4mLt4kmRYKqnQwsNcwDt9pNSHEol7UTFjwGmoR";
        $token = "3Sb5Z1ApauQffpGDYD7G";
        $receiveid = "ww377c91a81493c595";
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sVerifyEchoStr = $_GET['echostr'];

        $sEchoStr = "";
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            log_print($sEchoStr);
            // 验证URL成功
            return $sEchoStr;
        } else {
            log_print('回调失败');
            log_print("ERR: " . $errCode);
            return '回调失败';
        }
    }

    public function approvalCallback(){
        $encodingAesKey = "E4cLYufyxVlysTENuNE40C8UHee8wFMW1g6jnNI9mGo";
        $token = "IE89oKBvhvgkaSPmGlrIkcV";
        $receiveid = "ww377c91a81493c595";

        //校验
        //return $this->verify($token,$encodingAesKey,$receiveid,$_GET);
        //业务处理
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $_GET['msg_signature'];
        $sVerifyTimeStamp = $_GET['timestamp'];
        $sVerifyNonce = $_GET['nonce'];
        $sReqData = file_get_contents('php://input');//获取post过来的xml
        $sMsg = "";  // 解析之后的明文
        $errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sReqData, $sMsg);
//        $errCode = 0;
        if ($errCode == 0) {
            // 解密成功，sMsg即为xml格式的明文
//            var_dump($sMsg);
//            $sMsg = '<xml><ToUserName><![CDATA[wwddddccc7775555aaa]]></ToUserName><FromUserName><![CDATA[sys]]></FromUserName><CreateTime>1527838022</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[open_approval_change]]></Event><AgentID>1</AgentID><ApprovalInfo><ThirdNo><![CDATA[201806010001]]></ThirdNo><OpenSpName><![CDATA[付款]]></OpenSpName><OpenTemplateId><![CDATA[1234567890]]></OpenTemplateId><OpenSpStatus>1</OpenSpStatus><ApplyTime>1527837645</ApplyTime><ApplyUserName><![CDATA[xiaoming]]></ApplyUserName><ApplyUserId><![CDATA[1]]></ApplyUserId><ApplyUserParty><![CDATA[产品部]]></ApplyUserParty><ApplyUserImage><![CDATA[http://www.qq.com/xxx.png]]></ApplyUserImage><ApprovalNodes><ApprovalNode><NodeStatus>1</NodeStatus><NodeAttr>1</NodeAttr><NodeType>1</NodeType><Items><Item><ItemName><![CDATA[xiaohong]]></ItemName><ItemUserId><![CDATA[2]]></ItemUserId><ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage><ItemStatus>1</ItemStatus><ItemSpeech><![CDATA[]]></ItemSpeech><ItemOpTime>0</ItemOpTime></Item></Items></ApprovalNode></ApprovalNodes><NotifyNodes><NotifyNode><ItemName><![CDATA[xiaogang]]></ItemName><ItemUserId><![CDATA[3]]></ItemUserId><ItemImage><![CDATA[http://www.qq.com/xxx.png]]></ItemImage></NotifyNode></NotifyNodes><approverstep>0</approverstep></ApprovalInfo></xml>';
            $decodeMsg = json_decode(json_encode(simplexml_load_string($sMsg, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//            print_r($decodeMsg);
            log_print('请假审批');
            log_print($decodeMsg);
            $approvalInfo = $decodeMsg['ApprovalInfo'];
            if($approvalInfo['SpStatus']==1){
                // 保存审批记录
                $data = [
                    'date_string'    => date('Y-m-d',$decodeMsg['CreateTime']),
                    'user_id'    => $approvalInfo['Applyer']['UserId'],
                    'department'      => $approvalInfo['Applyer']['Party'],
                    'sp_status'      => $approvalInfo['SpStatus']
                ];
                $shenpiModel = new \app\api\model\ShenpiModel;
                $id = $shenpiModel->insertGetId($data);
                if ($id) {
                    return $this->success('提交成功', ['id' => $id]);
                } else {
                    return $this->error('提交失败');
                }
            }

        } else {
            print("ERR: " . $errCode . "\n\n");
        }


    }

    public function verify($token,$encodingAesKey,$receiveid,$get){
        $wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
        $sVerifyMsgSig = $get['msg_signature'];
        $sVerifyTimeStamp = $get['timestamp'];
        $sVerifyNonce = $get['nonce'];
        $sVerifyEchoStr = $get['echostr'];
        $sEchoStr = "";
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            log_print($sEchoStr);
            // 验证URL成功
            return $sEchoStr;
        } else {
            log_print('回调失败');
            log_print("ERR: " . $errCode);
            return '回调失败';
        }

    }

}
